package group

import (
	"common/mildware"
	"common/models"
	"common/validate"
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	"go.uber.org/zap"
	"strings"
)

func (h GHandler) GetAllGroup(c *gin.Context) {
	resp := new(models.RespData)
	req := new(models.PageInfo)
	var list []*models.GroupInfo
	if err := c.ShouldBindJSON(req); err != nil {
		errs, ok := err.(validator.ValidationErrors)
		if !ok {
			zap.L().Error("Group:GetAllGroup with invalid fail", zap.Error(err))
			resp.SendServerBusy(c)
			return
		} else {
			zap.L().Error("Group:GetAllGroup with invalid fail", zap.Error(errs))
			resp.SendCodeWithMsg(c, models.CodeInvalidParam, validate.RemoveTopStruct(errs.Translate(validate.Trans)))
			return
		}
	}
	//获得Id
	ID, _, _, err := mildware.GetCyrrentUserID(c)
	if err != nil {
		zap.L().Error("Group:CreateGroup  mildware.GetCyrrentUserID", zap.Error(err))
		resp.SendServerBusy(c)
		return
	}
	//userinfo
	exist, userInfo, err := h.M.UserCheckId(ID)
	if err != nil {
		zap.L().Error("Group:CreateGroup  h.M.UserCheckId", zap.Error(err))
		resp.SendServerBusy(c)
		return
	}
	groupMap := make(map[string]struct{})
	if exist {
		groups := strings.Split(userInfo.Groups, "|")
		for _, group := range groups {
			if group == "" {
				continue
			}
			if _, ok := groupMap[group]; ok {
				continue
			}
			groupMap[group] = struct{}{}
			info, err := h.M.GroupSelectByID(group)
			if err != nil {
				zap.L().Error("Group:CreateGroup  h.M.GroupSelectByID", zap.Error(err))
				resp.SendServerBusy(c)
				return
			}
			list = append(list, info)
		}
	}
	resp.Data = list
	resp.Count = int64(len(list))
	resp.SendSuccess(c)
	return
}
